import { useEffect } from "react";
import { Outlet, useNavigate, useLoaderData } from "react-router-dom";
import { useSelector, useDispatch } from 'react-redux';
import {
  changeInitData,
  changeCurrentCateId,
} from '@/stores/cartSlice';

import { selectTabs, selectShoppingCart } from "./stores/cartSlice";

import { Image } from 'react-vant';
import styles from './views/css/app/app.module.scss'
import { ShoppingCartO, Contact } from '@react-vant/icons';

function App() {
  const navigate = useNavigate()
  const dispatch = useDispatch();

  const homeData = useLoaderData();
  dispatch(changeInitData(homeData))

  const tabs = useSelector(selectTabs)
  const shoppingCart = useSelector(selectShoppingCart)

  // 监听购物车数据变化时存储到本地
  useEffect(() => {
    localStorage.setItem('shoppingCart', JSON.stringify(shoppingCart))
  }, [shoppingCart])

  function changeTab(sort) {
    dispatch(changeCurrentCateId({ sort }))
    navigate('/cate/' + sort, { replace: true })
  }

  return (
    <div className={styles.app}>
      <header>
        <div className={styles.header + " container"}>
          <div className={styles.left}>
            <div className={styles.logo}>
              <Image fit="cover" width='100%' height='100%' src="https://oss.51cocoa.com/themes/site/img/logo.png" />
            </div>
            <ul>
              <li onClick={() => navigate('/', { replace: true })}>首页</li>
              {tabs?.content.map(tab => (
                <li key={tab.sort} onClick={() => changeTab(tab.sort)}>{tab.name}</li>
              ))}
            </ul>
          </div>

          <div className={styles.right}>
            <ul>
              <li>消息</li>
              {
                false ? (<li onClick={() => navigate('/login')}>登录/注册</li>) : (
                  <li onClick={() => navigate('/my')}><Contact color="#684029" fontSize="22px" /></li>)
              }
              <li onClick={() => navigate('/cart')} ><ShoppingCartO color="#684029" fontSize="22px" /></li >
            </ul >
          </div >
        </div >
      </header >

      <Outlet />

      <div className={styles.footer}>
        <div className={"container " + styles.typeright}>
          <div className={styles.item}>
            <div>关于我们</div>
            <p>团队：雅清集团</p>
            <p>联系电话：189 xxxx 4366</p>
          </div>
          <div className={styles.item}>
            <div>订购时间</div>
            <p>白天：10:00-20:00</p>
            <p>晚上不营业</p>
          </div>
        </div>
      </div>
    </div >
  )
}

export default App
